package protocols;

import exceptions.ExAddressInput;

public class ARP implements EthernetIIPayload{
	private int HTYPE;
	private int PTYPE;
	private int HLEN;
	private int PLEN;
	private int OPER;
	private EthernetII.MACaddress SHA;
	private IPv4.IPv4address SPA;
	private EthernetII.MACaddress THA;
	private IPv4.IPv4address TPA;
	
	public ARP (int htype, int ptype, int hlen, int plen, int oper, EthernetII.MACaddress sha, IPv4.IPv4address spa, EthernetII.MACaddress tha, IPv4.IPv4address tpa){
		HTYPE = htype;
		PTYPE = ptype;
		HLEN = hlen;
		PLEN = plen;
		OPER = oper;
		SHA = sha;
		SPA = spa;
		THA = tha;
		TPA = tpa;
	}
	public ARP (int oper, EthernetII.MACaddress sha, IPv4.IPv4address spa, EthernetII.MACaddress tha, IPv4.IPv4address tpa){
		this(1, 0x0800, 6, 4, oper, sha, spa, tha, tpa);
	}
	public int length (EthernetIIPayload payload){
		return 24;
	}
	@Override
	public String toString(){
		String s = new String();
		s=String.format("%04x%04x%02x%02x%04x"+SHA.toString1()+SPA.toString1()+THA.toString1()+TPA.toString1(),HTYPE,PTYPE,HLEN,PLEN,OPER);
		return s;

	}
	public static EthernetII request(EthernetII.MACaddress sha, IPv4.IPv4address spa, IPv4.IPv4address tpa) throws ExAddressInput{
		ARP arpPacket = new ARP(1, sha, spa, new EthernetII.MACaddress("00:00:00:00:00:00"), tpa);
		EthernetII ARPframe = new EthernetII(new EthernetII.MACaddress("ff:ff:ff:ff:ff:ff"),sha,"ARP", arpPacket);
		return ARPframe;
	}
	public static EthernetII reply(EthernetII f, EthernetII.MACaddress hwa){
		EthernetII.MACaddress tha = f.getSourceAddress();
		ARP framedata = (ARP) f.getPayload();
		IPv4.IPv4address tpa = framedata.SPA;
		IPv4.IPv4address spa = framedata.TPA;
		ARP ARPreply = new ARP(2, hwa, spa, tha, tpa);
		return new EthernetII(tha, hwa, "ARP", ARPreply);
		
	}
	public int length() {
		return 34;
	}

}
